package cc.wanforme.chipmunity.system.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cc.wanforme.chipmunity.common.bean.WebResponse;
import cc.wanforme.chipmunity.system.event.BaseEvent;
import cc.wanforme.chipmunity.system.event.SectionEvent;
import cc.wanforme.chipmunity.system.mapper.SectionMapper;
import cc.wanforme.chipmunity.system.mapper.SubjectMapper;
import cc.wanforme.chipmunity.system.po.Section;
import cc.wanforme.chipmunity.system.po.Subject;
import cc.wanforme.chipmunity.system.service.interfaces.SectionService;

/**
 * @author wanne
 * 2019年8月17日
 * 
 */
@Service
public class SectionServiceImpl implements SectionService, ApplicationEventPublisherAware {

	private ApplicationEventPublisher publisher;
	
	@Autowired
	private SectionMapper sectionMapper;
	
	@Autowired
	private SubjectMapper subjectMapper;
	
	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		this.publisher = applicationEventPublisher;
	}
	
	
	@Override
	public WebResponse saveSection(Section section) {
		if(StringUtils.isBlank(section.getName())) {
			return WebResponse.fail("板块名不能为空");
		}
		sectionMapper.insertSection(section);
		return WebResponse.success("新板块添加成功");
	}

	@Transactional
	@Override
	public WebResponse updateService(Section section) {
		if(section.getId() == null || StringUtils.isBlank(section.getName())) {
			return WebResponse.fail("信息不完整");
		}
		
		// 更新主题的板块名
		List<Subject> subjects = subjectMapper.listSubjectBySection(section.getName());
		for (Subject subject : subjects) {
			subject.setSectionName(section.getName());
		}
		
		sectionMapper.updateSection(section);
		//publisher.publishEvent(new SectionEvent(section, BaseEvent.OperateType.UPDATE));
		return WebResponse.success("修改成功");
	}
	
	@Transactional
	@Override
	public WebResponse removeSection(Section section) {
		if(section.getId() == null || StringUtils.isBlank(section.getName())){
			return WebResponse.fail("信息不完整");
		}
		
		publisher.publishEvent(new SectionEvent(section, BaseEvent.OperateType.DELETE));
		sectionMapper.deleteSection(section);
		return WebResponse.success("删除成功");
	}
	

}
